package com.zb.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.AccounLoginInfo;
import com.zb.entity.ExportFieldAttrVo;
import com.zb.entity.ExportFieldVo;
import com.zb.entity.ZjWorkExportField;
import com.zb.mapper.ZjWorkExportFieldMapper;
import com.zb.service.ZjWorkExportFieldService;
import com.zb.vo.WorkSysInitExportFieldVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 工单导出字段表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2024-03-04
 */
@Service
public class ZjWorkExportFieldServiceImpl extends ServiceImpl<ZjWorkExportFieldMapper, ZjWorkExportField> implements ZjWorkExportFieldService {
    @Resource
    private ZjWorkExportFieldMapper workExportFieldMapper;

    // 获取工单系统初始导出字段
    @Override
    public List<WorkSysInitExportFieldVo> getOrderSysInitExportFields() {
        return workExportFieldMapper.getOrderSysInitExportFields();
    }

    // 保存导出字段
    @Override
    public void save(AccounLoginInfo loginInfo, ExportFieldVo exportFieldVo) {
        QueryWrapper<ZjWorkExportField> wrapper = new QueryWrapper<>();
        wrapper.select("id")
                .eq("cust_acc_id", loginInfo.getCustAccId()).eq("account_id", loginInfo.getId());
        ZjWorkExportField exportField = this.getOne(wrapper);
        if (null != exportField) {
            exportField.setField(JSON.toJSONString(exportFieldVo.getFieldAttrs()));
            this.updateById(exportField);
            return;
        }
        exportField = new ZjWorkExportField();
        exportField.setId(IdWorker.getId());
        exportField.setCustAccId(loginInfo.getCustAccId());
        exportField.setAccountId(loginInfo.getId());
        exportField.setField(JSON.toJSONString(exportFieldVo.getFieldAttrs()));
        this.save(exportField);
    }

    // 获取工单导出字段
    @Override
    public List<ExportFieldAttrVo> getOrderExportFields(AccounLoginInfo loginInfo) {
        QueryWrapper<ZjWorkExportField> wrapper = new QueryWrapper<>();
        wrapper.select("field")
                .eq("cust_acc_id", loginInfo.getCustAccId()).eq("account_id", loginInfo.getId());
        ZjWorkExportField exportField = this.getOne(wrapper);
        if (null == exportField || StringUtils.isBlank(exportField.getField())) {
            return new ArrayList<>();
        }
        return JSON.parseArray(exportField.getField(), ExportFieldAttrVo.class);
    }
}
